<!doctype html><html lang dir=ltr><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><title>【第4周笔记】程序的控制结构 | Python | Hui.Ke - Blog</title><meta name=generator content="Hugo Eureka 0.9.3"><link rel=stylesheet href=https://b.hui.ke/css/eureka.min.9cec6350e37e534b0338fa9a085bf06855de3b0f2dcf857e792e5e97b07ea905d4d5513db554cbc26a9c3da622bae92d.css><script defer src=https://b.hui.ke/js/eureka.min.fa9a6bf6d7a50bb635b4cca7d2ba5cf3dfb095ae3798773f1328f7950028b48c17d06276594e1b5f244a25a6c969a705.js></script>
<link rel=preconnect href=https://fonts.googleapis.com><link rel=preconnect href=https://fonts.gstatic.com crossorigin><link rel=preload href="https://fonts.googleapis.com/css2?family=Lora:wght@400;600;700&family=Noto+Serif+SC:wght@400;600;700&display=swap" as=style onload='this.onload=null,this.rel="stylesheet"'><link rel=stylesheet href=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/styles/vs.min.css media=print onload='this.media="all",this.onload=null' crossorigin><script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/highlight.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/bash.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/ini.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/json.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/php.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/python.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/shell.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/sql.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/x86asm.min.js crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.4.0/build/languages/xml.min.js crossorigin></script>
<link rel=stylesheet href=https://b.hui.ke/css/highlightjs.min.2958991528e43eb6fc9b8c4f2b8e052f79c4010718e1d1e888a777620e9ee63021c2c57ec7417a3108019bb8c41943e6.css media=print onload='this.media="all",this.onload=null'><script defer type=text/javascript src=https://lib.baomitu.com/font-awesome/6.1.1/js/all.min.js></script>
<link rel=stylesheet href=https://cdn.jsdelivr.net/npm/katex@0.15.2/dist/katex.min.css integrity=sha384-MlJdn/WNKDGXveldHDdyRP1R4CTHr3FeuDNfhsLPYrq2t0UBkUdK2jyTnXPEK1NQ media=print onload='this.media="all",this.onload=null' crossorigin><script defer src=https://cdn.jsdelivr.net/npm/katex@0.15.2/dist/katex.min.js integrity=sha384-VQ8d8WVFw0yHhCk5E8I86oOhv48xLpnDZx5T9GogA/Y84DcCKWXDmSDfn13bzFZY crossorigin></script>
<script defer src=https://cdn.jsdelivr.net/npm/katex@0.15.2/dist/contrib/auto-render.min.js integrity=sha384-+XBljXPPiv+OzfbB3cVmLHf4hdUFHlWNZN5spNQ7rmHTXpd7WvJum6fIACpNNfIR crossorigin></script>
<script>document.addEventListener("DOMContentLoaded",function(){renderMathInElement(document.body,{delimiters:[{left:"$$",right:"$$",display:!0},{left:"$",right:"$",display:!1},{left:"\\(",right:"\\)",display:!1},{left:"\\[",right:"\\]",display:!0}]})})</script><script defer src=https://cdn.jsdelivr.net/npm/mermaid@8.14.0/dist/mermaid.min.js integrity=sha384-atOyb0FxAgN9LyAc6PEf9BjgwLISyansgdH8/VXQH8p2o5vfrRgmGIJ2Sg22L0A0 crossorigin></script>
<link rel=icon type=image/png sizes=32x32 href=https://b.hui.ke/icon_hub7ca0b5404c6d576559b2bd22c64b0e5_2009_32x32_fill_box_center_3.png><link rel=apple-touch-icon sizes=180x180 href=https://b.hui.ke/icon_hub7ca0b5404c6d576559b2bd22c64b0e5_2009_180x180_fill_box_center_3.png><meta name=description content="  课程笔记和选择题"><script type=application/ld+json>{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Docs","item":"https://b.hui.ke/docs/"},{"@type":"ListItem","position":2,"name":"Python","item":"https://b.hui.ke/docs/python/"},{"@type":"ListItem","position":3,"name":"【第4周笔记】程序的控制结构","item":"https://b.hui.ke/docs/python/4/"}]}</script><script type=application/ld+json>{"@context":"https://schema.org","@type":"Article","mainEntityOfPage":{"@type":"WebPage","@id":"https://b.hui.ke/docs/python/4/"},"headline":"【第4周笔记】程序的控制结构 | Python | Hui.Ke - Blog","datePublished":"2022-04-07T08:57:43+08:00","dateModified":"2022-04-11T11:30:43+08:00","wordCount":2690,"author":{"@type":"Person","name":"Hui.Ke"},"publisher":{"@type":"Person","name":"Hui.Ke","logo":{"@type":"ImageObject","url":"https://b.hui.ke/icon.png"}},"description":"\u003cp\u003e  课程笔记和选择题\u003c\/p\u003e"}</script><meta property="og:title" content="【第4周笔记】程序的控制结构 | Python | Hui.Ke - Blog"><meta property="og:type" content="article"><meta property="og:image" content="https://b.hui.ke/icon.png"><meta property="og:url" content="https://b.hui.ke/docs/python/4/"><meta property="og:description" content="  课程笔记和选择题"><meta property="og:site_name" content="Hui.Ke - Blog"><meta property="article:published_time" content="2022-04-07T08:57:43+08:00"><meta property="article:modified_time" content="2022-04-11T11:30:43+08:00"><meta property="article:section" content="docs"><meta property="article:tag" content="分支结构"><meta property="article:tag" content="循环"><meta property="article:tag" content="随机数"><meta property="og:see_also" content="https://b.hui.ke/docs/python/20/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/10/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/19/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/9/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/18/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/8/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/17/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/7/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/16/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/6/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/15/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/5/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/14/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/13/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/3/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/12/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/2/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/11/"><meta property="og:see_also" content="https://b.hui.ke/docs/python/1/"><script>!function(e){"use strict";!function(){var i,s=window,o=document,a=e,c="".concat("https:"===o.location.protocol?"https://":"http://","sdk.51.la/js-sdk-pro.min.js"),n=o.createElement("script"),r=o.getElementsByTagName("script")[0];n.type="text/javascript",n.setAttribute("charset","UTF-8"),n.async=!0,n.src=c,n.id="LA_COLLECT",a.d=n,i=function(){s.LA.ids.push(a)},s.LA?s.LA.ids&&i():(s.LA=e,s.LA.ids=[],i()),r.parentNode.insertBefore(n,r)}()}({id:"Jgb8aUbG5e3rqhrs",ck:"Jgb8aUbG5e3rqhrs",autoTrack:!0,hashMode:!0})</script><body class="flex min-h-screen flex-col"><header class="min-h-16 pl-scrollbar bg-secondary-bg fixed z-50 flex w-full items-center shadow-sm"><div class="mx-auto w-full max-w-screen-xl"><script>let storageColorScheme=localStorage.getItem("lightDarkMode");((storageColorScheme=="Auto"||storageColorScheme==null)&&window.matchMedia("(prefers-color-scheme: dark)").matches||storageColorScheme=="Dark")&&document.getElementsByTagName("html")[0].classList.add("dark")</script><nav class="flex items-center justify-between flex-wrap px-4 py-4 md:py-0"><a href=/ class="me-6 text-primary-text text-xl font-bold">Hui.Ke - Blog</a>
<button id=navbar-btn class="md:hidden flex items-center px-3 py-2" aria-label="Open Navbar">
<i class="fas fa-bars"></i></button><div id=target class="hidden block md:flex md:grow md:justify-between md:items-center w-full md:w-auto text-primary-text z-20"><div class="md:flex md:h-16 text-sm md:grow pb-4 md:pb-0 border-b md:border-b-0"><a href=/posts/ class="block mt-4 md:inline-block md:mt-0 md:h-(16-4px) md:leading-(16-4px) box-border md:border-t-2 md:border-b-2 border-transparent me-4">Posts</a>
<a href=/docs/ class="block mt-4 md:inline-block md:mt-0 md:h-(16-4px) md:leading-(16-4px) box-border md:border-t-2 md:border-b-2 selected-menu-item me-4">Docs</a>
<a href=/categories/ class="block mt-4 md:inline-block md:mt-0 md:h-(16-4px) md:leading-(16-4px) box-border md:border-t-2 md:border-b-2 border-transparent me-4">Categories</a>
<a href=/series/ class="block mt-4 md:inline-block md:mt-0 md:h-(16-4px) md:leading-(16-4px) box-border md:border-t-2 md:border-b-2 border-transparent me-4">Series</a>
<a href=/tags/ class="block mt-4 md:inline-block md:mt-0 md:h-(16-4px) md:leading-(16-4px) box-border md:border-t-2 md:border-b-2 border-transparent me-4">Tags</a>
<a href=/love/ class="block mt-4 md:inline-block md:mt-0 md:h-(16-4px) md:leading-(16-4px) box-border md:border-t-2 md:border-b-2 border-transparent me-4">Love</a>
<a href=/about/ class="block mt-4 md:inline-block md:mt-0 md:h-(16-4px) md:leading-(16-4px) box-border md:border-t-2 md:border-b-2 border-transparent me-4">About</a></div><div class=flex><div class="relative pt-4 md:pt-0"><div class="cursor-pointer hover:text-eureka" id=lightDarkMode><i class="fas fa-adjust"></i></div><div class="fixed hidden inset-0 opacity-0 h-full w-full cursor-default z-30" id=is-open></div><div class="absolute flex flex-col start-0 md:start-auto end-auto md:end-0 hidden bg-secondary-bg w-48 rounded py-2 border border-tertiary-bg cursor-pointer z-40" id=lightDarkOptions><span class="px-4 py-1 hover:text-eureka" name=Light>Light</span>
<span class="px-4 py-1 hover:text-eureka" name=Dark>Dark</span>
<span class="px-4 py-1 hover:text-eureka" name=Auto>Auto</span></div></div></div></div><div class="fixed hidden inset-0 opacity-0 h-full w-full cursor-default z-0" id=is-open-mobile></div></nav><script>let element=document.getElementById("lightDarkMode");storageColorScheme==null||storageColorScheme=="Auto"?document.addEventListener("DOMContentLoaded",()=>{window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",switchDarkMode)}):storageColorScheme=="Light"?(element.firstElementChild.classList.remove("fa-adjust"),element.firstElementChild.setAttribute("data-icon","sun"),element.firstElementChild.classList.add("fa-sun")):storageColorScheme=="Dark"&&(element.firstElementChild.classList.remove("fa-adjust"),element.firstElementChild.setAttribute("data-icon","moon"),element.firstElementChild.classList.add("fa-moon")),document.addEventListener("DOMContentLoaded",()=>{getcolorscheme(),switchBurger()})</script></div></header><main class="grow pt-16"><div class=pl-scrollbar><div class="mx-auto w-full max-w-screen-xl lg:px-4 xl:px-8"><div class=lg:pt-12><div class="flex flex-col md:flex-row bg-secondary-bg rounded"><div class="md:w-1/4 lg:w-1/5 border-e"><div class="sticky top-16 pt-6"><div id=sidebar-title class="md:hidden mx-4 px-2 pt-4 pb-2 md:border-b text-tertiary-text md:text-primary-text"><span class=font-semibold>Table of Contents</span>
<i class='fas fa-caret-right ms-1'></i></div><div id=sidebar-toc class="hidden md:block overflow-y-auto mx-6 md:mx-0 pe-6 pt-2 md:max-h-doc-sidebar bg-primary-bg md:bg-transparent"><div class="flex flex-wrap ms-4 -me-2 p-2 bg-secondary-bg md:bg-primary-bg rounded"><a class=hover:text-eureka href=https://b.hui.ke/docs/python/>Python</a></div><ul class=ps-6><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/20/>期末测验</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/10/>【第9+周笔记】全课程总结与学习展望</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/19/>【第9周程序】计算生态纵览</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/9/>【第9周笔记】计算生态纵览</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/18/>【第8周程序】程序设计方法学</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/8/>【第8周笔记】程序设计方法学</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/17/>【第7周程序】文件和数据格式化</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/7/>【第7周笔记】文件和数据格式化</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/16/>【第6周程序】组合数据类型</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/6/>【第6周笔记】组合数据类型</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/15/>【第5周程序】函数和代码复用</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/5/>【第5周笔记】函数和代码复用</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/14/>【第4周程序】程序的控制结构</a></div></li><li class=py-2><div><a class="text-eureka hover:text-eureka" href=https://b.hui.ke/docs/python/4/>【第4周笔记】程序的控制结构</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/13/>【第3周程序】基本数据类型</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/3/>【第3周笔记】基本数据类型</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/12/>【第2周程序】Python 基本图形绘制</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/2/>【第2周笔记】Python 基本图形绘制</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/11/>【第1周程序】Python 基本语法元素</a></div></li><li class=py-2><div><a class=hover:text-eureka href=https://b.hui.ke/docs/python/1/>【第1周笔记】Python 基本语法元素</a></div></li></ul></div></div></div><div class="w-full md:w-3/4 lg:w-4/5 pb-8 pt-2 md:pt-8"><div class=flex><div class="w-full lg:w-3/4 px-6"><article class=prose><h1 class=mb-4>【第4周笔记】程序的控制结构</h1><div class="text-tertiary-text not-prose mt-2 flex flex-row flex-wrap items-center"><div class="me-6 my-2"><i class="fas fa-calendar me-1"></i>
<span>2022-04-07</span></div><div class="me-6 my-2"><i class="fa-solid fa-pen-to-square me-1"></i>
<span>2022-04-11</span></div><div class="me-6 my-2"><i class="fas fa-clock me-1"></i>
<span>6 min read</span></div><div class="me-6 my-2"><i class="fas fa-folder me-1"></i>
<a href=https://b.hui.ke/categories/it/ class=hover:text-eureka>IT</a></div><div class="me-6 my-2"><i class="fas fa-th-list me-1"></i>
<a href=https://b.hui.ke/series/python/ class=hover:text-eureka>Python</a></div><div class="me-6 my-2"><i class="fa-solid fa-eye me-1"></i>
<span id=busuanzi_value_page_pv><i class="fa fa-spinner fa-spin"></i></span> Hits</div></div><p>  课程笔记和选择题</p><h2 id=notes>Notes</h2><h3 id=单分支结构>单分支结构</h3><p>  根据判断条件结果而选择不同向前路径的运行方式</p><pre><code class=language-python>if &lt;条件&gt; :
    &lt;语句块&gt;
</code></pre><h3 id=二分支结构>二分支结构</h3><pre><code class=language-python>if &lt;条件&gt; :
    &lt;语句块1&gt;
else :
    &lt;语句块2&gt;
</code></pre><p>  紧凑形式：适用于简单表达式的二分支结构</p><p>&lt;表达式1> if &lt;条件> else &lt;表达式2></p><h3 id=多分支结构>多分支结构</h3><pre><code class=language-python>if &lt;条件1&gt; :
    &lt;语句块1&gt;
elif &lt;条件2&gt; :
    &lt;语句块2&gt;
    ……
else :
    &lt;语句块N&gt;
</code></pre><blockquote><p>注意多条件之间的包含关系和变量取值范围的覆盖</p></blockquote><h3 id=条件判断及组合>条件判断及组合</h3><table><thead><tr><th style=text-align:center>操作符</th><th style=text-align:center>数学符号</th><th style=text-align:center>描述</th></tr></thead><tbody><tr><td style=text-align:center>&lt;</td><td style=text-align:center>&lt;</td><td style=text-align:center>小于</td></tr><tr><td style=text-align:center>&lt;=</td><td style=text-align:center>≤</td><td style=text-align:center>小于等于</td></tr><tr><td style=text-align:center>>=</td><td style=text-align:center>≥</td><td style=text-align:center>大于等于</td></tr><tr><td style=text-align:center>></td><td style=text-align:center>></td><td style=text-align:center>大于</td></tr><tr><td style=text-align:center>==</td><td style=text-align:center>=</td><td style=text-align:center>等于</td></tr><tr><td style=text-align:center>!=</td><td style=text-align:center>≠</td><td style=text-align:center>不等于</td></tr></tbody></table><p>  用于条件组合的三个保留字</p><table><thead><tr><th style=text-align:center>操作符及使用</th><th style=text-align:center>描述</th></tr></thead><tbody><tr><td style=text-align:center>x and y</td><td style=text-align:center>两个条件 x 和 y 的逻辑<strong>与</strong></td></tr><tr><td style=text-align:center>x or y</td><td style=text-align:center>两个条件 x 和 y 的逻辑<strong>或</strong></td></tr><tr><td style=text-align:center>not x</td><td style=text-align:center>条件 x 的逻辑<strong>非</strong></td></tr></tbody></table><h3 id=异常处理>异常处理</h3><p>  异常处理的基本使用</p><pre><code class=language-python>try :
    &lt;语句块1&gt;
except :
    &lt;语句块2&gt;

try :
    &lt;语句块1&gt;
except &lt;异常类型&gt; :     # 标注异常类型后，仅响应此类异常，异常类型名字等同于变量名
    &lt;语句块2&gt;
</code></pre><p>  异常处理的高级使用</p><pre><code class=language-python>try :
    &lt;语句块1&gt;
except :
    &lt;语句块2&gt;
else :
    &lt;语句块3&gt;     # else 对应语句块 3 在不发生异常时实行
finally :
    &lt;语句块4&gt;     # finally 对应语句块 4 一定执行
</code></pre><h3 id=遍历循环>遍历循环</h3><pre><code class=language-python>for &lt;循环变量&gt; in &lt;遍历结构&gt; ：     # 从遍历结构中逐一提取元素，放在循环变量中
    &lt;语句块&gt;
</code></pre><p>  由保留字 for 和 in 组成，完整遍历所有元素后结束</p><p>  每次循环，所获得元素放入循环变量，并执行一次语句块</p><ol><li>计数循环（N 次）</li></ol><pre><code class=language-python>for i in range(N) :     # 遍历由 range() 函数产生的数字序列，产生循环
    &lt;语句块&gt;

# 举例
&gt;&gt;&gt; for i in range(5) :
    print(&quot;Hello:&quot;,i)

# 输出
Hello: 0
Hello: 1
Hello: 2
Hello: 3
Hello: 4
</code></pre><ol start=2><li>计数循环（特定次）</li></ol><pre><code class=language-python>for i in range(M,N,K) :
    &lt;语句块&gt;

# 举例
&gt;&gt;&gt; for i in range(1,6,2) :
    print(&quot;Hello:&quot;,i)

# 输出
Hello: 1
Hello: 3
Hello: 5
</code></pre><ol start=3><li>字符串遍历循环</li></ol><pre><code class=language-python>for c in s :     # s 是字符串，遍历字符串每个字符，产生循环
    &lt;语句块&gt;

# 举例
&gt;&gt;&gt; for c in &quot;Python123&quot; :
    print(c, end=&quot;,&quot;)

# 输出
P,y,t,h,o,n,1,2,3,
</code></pre><ol start=4><li>列表遍历循环</li></ol><pre><code class=language-python>for item in ls :     # ls 是一个列表，遍历其每个元素，产生循环
    &lt;语句块&gt;

# 举例
&gt;&gt;&gt; for item in [123, &quot;PY&quot;, 456] :
    print(item, end=&quot;,&quot;)

# 输出
123,PY,456,
</code></pre><ol start=5><li>文件遍历循环</li></ol><pre><code class=language-python>for line in fi :     # fi 是一个文件标识符，遍历其每行，产生循环
    &lt;语句块&gt;
</code></pre><h3 id=无限循环>无限循环</h3><p>  由条件控制的循环运行方式</p><pre><code class=language-python>while &lt;条件&gt; :     # 反复执行语句块，直到条件不满足时结束
    &lt;语句块&gt;
</code></pre><h3 id=循环控制保留字>循环控制保留字</h3><p>break 跳出并结束当前整个循环，执行循环后的语句</p><p>continue 结束当次循环，继续执行后续次数循环</p><p>break 和 continue 可以与 for 和 while 循环搭配使用</p><pre><code class=language-python>&gt;&gt;&gt; for c in &quot;PYTHON&quot; :
    if c == &quot;T&quot; :
        continue
    print(c, end=&quot;&quot;)

输出：PYHON

&gt;&gt;&gt; for c in &quot;PYTHON&quot; :
    if c == &quot;T&quot; :
        break
    print(c, end=&quot;&quot;)

输出：PY

&gt;&gt;&gt; s = &quot;PYTHON&quot; 
&gt;&gt;&gt; while s != &quot;&quot; :
    for c in s :
        print(c, end=&quot;&quot;)
    s = s[:-1]

输出：PYTHONPYTHOPYTHPYTPYP

&gt;&gt;&gt; s = &quot;PYTHON&quot; 
&gt;&gt;&gt; while s != &quot;&quot; :
    for c in s :
        if c == &quot;T&quot; :
            break     # break 仅跳出当前最内层循环
        print(c, end=&quot;&quot;)
    s = s[:-1]

输出：PYPYPYPYPYP
</code></pre><h3 id=循环与-else>循环与 else</h3><pre><code class=language-python>for &lt;变量&gt; in &lt;遍历结构&gt; :
    &lt;语句块1&gt;
else :
    &lt;语句块2&gt;

while &lt;条件&gt; :
    &lt;语句块1&gt;
else :
    &lt;语句块2&gt;
</code></pre><p>  当循环没有被 break 语句退出时，执行 else 语句块</p><p>  else 语句块作为"正常"完成循环的奖励</p><p>  这里 else 的用法与异常处理中 else 用法相似</p><pre><code class=language-python>&gt;&gt;&gt; for c in &quot;PYTHON&quot; :
        if c == &quot;T&quot; :
            continue
        print(c, end=&quot;&quot;)
    else :
        print(&quot;正常退出&quot;)

输出：PYHON正常退出

&gt;&gt;&gt; for c in &quot;PYTHON&quot; :
        if c == &quot;T&quot; :
            break
        print(c, end=&quot;&quot;)
    else :
        print(&quot;正常退出&quot;)

输出：PY
</code></pre><h3 id=random-库基本介绍>random 库基本介绍</h3><p>random 库是使用随机数的 Python 标准库</p><p>伪随机数: 采用梅森旋转算法生成的（伪）随机序列中元素</p><p>random 库主要用于生成随机数</p><p>使用 random 库: import random</p><p>random 库包括两类函数，常用共 8 个</p><p>基本随机数函数：seed()、random()</p><p>扩展随机数函数：randint()、getrandbits()、uniform()、randrange()、choice()、shuffle()</p><h3 id=基本随机数函数>基本随机数函数</h3><table><thead><tr><th style=text-align:center>函数</th><th style=text-align:center>描述</th><th style=text-align:center>举例</th><th style=text-align:center>结果</th></tr></thead><tbody><tr><td style=text-align:center>seed(a=None)</td><td style=text-align:center>初始化给定的随机数种子，默认为当前系统时间</td><td style=text-align:center>random.seed(10)</td><td style=text-align:center>产生种子 10 对应的序列</td></tr><tr><td style=text-align:center>random()</td><td style=text-align:center>生成一个 [0.0, 1.0) 之间的随机小数</td><td style=text-align:center>random.random()</td><td style=text-align:center>0.5714025946899135</td></tr></tbody></table><pre><code class=language-python>&gt;&gt;&gt; import random
&gt;&gt;&gt; random.seed(10)
&gt;&gt;&gt; random.random()
0.5714025946899135
&gt;&gt;&gt; random.random()
0.4288890546751146
……

&gt;&gt;&gt; import random
&gt;&gt;&gt; random.seed(10)
&gt;&gt;&gt; random.random()
0.5714025946899135
&gt;&gt;&gt; random.seed(10)
&gt;&gt;&gt; random.random()
0.5714025946899135
</code></pre><h3 id=扩展随机数函数>扩展随机数函数</h3><table><thead><tr><th style=text-align:center>函数</th><th style=text-align:center>描述</th><th style=text-align:center>举例</th><th style=text-align:center>输出</th></tr></thead><tbody><tr><td style=text-align:center>randint(a,b)</td><td style=text-align:center>生成一个 [a, b] 之间的整数</td><td style=text-align:center>random.randint(10, 100)</td><td style=text-align:center>64</td></tr><tr><td style=text-align:center>randrange(m, n[, k])</td><td style=text-align:center>生成一个 [m, n) 之间以 k 为步长的随机整数</td><td style=text-align:center>random.randrange(10, 100, 10)</td><td style=text-align:center>80</td></tr><tr><td style=text-align:center>getrandbits(k)</td><td style=text-align:center>生成一个 k 比特长的随机整数</td><td style=text-align:center>random.getrandbits(16)</td><td style=text-align:center>37885</td></tr><tr><td style=text-align:center>uniform(a, b)</td><td style=text-align:center>生成一个 [a, b] 之间的随机小数</td><td style=text-align:center>random.uniform(10, 100)</td><td style=text-align:center>13.096321648808136</td></tr><tr><td style=text-align:center>choice(seq)</td><td style=text-align:center>从序列 seq 中随机选择一个元素</td><td style=text-align:center>random.choice([1,2,3,4,5,6,7,8,9])</td><td style=text-align:center>8</td></tr><tr><td style=text-align:center>shuffle(seq)</td><td style=text-align:center>将序列 seq 中元素随机排列，返回打乱后的序列</td><td style=text-align:center>s=[1,2,3,4,5,6,7,8,9];random.shuffle(s);print(s)</td><td style=text-align:center>[3, 5, 8, 9, 6, 1, 2, 7, 4]</td></tr></tbody></table><h2 id=测验-4>测验 4</h2><ol><li>哪个选项不符合以下程序空白处的语法要求？A</li></ol><pre><code class=language-python>for var in ___ :
    print(var)
</code></pre><pre><code>A. {1;2;3;4;5}

B. (1,2,3)

C. &quot;Hello&quot;

D. range(0,10)
</code></pre><ul><li>for……in……中 in 的后面需要是一个迭代类型（组合类型），{1;2;3;4;5} 不是 Python 的有效数据类型。</li></ul><ol start=2><li>哪个选项是以下程序的输出结果？C</li></ol><pre><code class=language-python>for i in range(0, 2) :
    print(i)
</code></pre><pre><code>A. 1

B. 0 1 2

C. 0 1

D. 1 2
</code></pre><ul><li>range(0, 2) 输出两个值：0 和 1。</li></ul><ol start=3><li>哪个选项给出了以下程序的输出次数？C</li></ol><pre><code class=language-python>k = 10000
while k &gt; 1 :
    print(k)
    k = k / 2
</code></pre><pre><code>A. 15

B. 13

C. 14

D. 1000
</code></pre><ul><li>请跟随程序计算或在 IDLE 中运行程序获得结果。</li></ul><ol start=4><li><p>哪个选项是程序的三种基本结构？C</p><p>A. 过程结构，循环结构，分支结构</p><p>B. 过程结构，对象结构，函数结构</p><p>C. 顺序结构，循环结构，分支结构</p><p>D. 顺序结构，跳转结构，循环结构</p></li></ol><ul><li>无对象结构、跳转结构、过程结构等说法。</li></ul><ol start=5><li><p>哪个选项关于循环结构的描述是错误的？C</p><p>A. 循环是一种程序的基本控制结构</p><p>B. 循环是程序根据条件判断结果向后反复执行的一种运行方式</p><p>C. 死循环无法退出，没有任何作用</p><p>D. 条件循环和遍历循环结构都是基本的循环结构</p></li></ol><ul><li>死循环能够用于测试性能，形式上的死循环可以用 break 来退出，例如：</li></ul><pre><code class=language-python>x = 10
while True :
    x = x - 1
    if x == 1 :
        break
</code></pre><ul><li>死循环是有其作用的。</li></ul><ol start=6><li><p>关于 Python 语句 P=-P，哪个选项的描述是正确的？B</p><p>A. P 的绝对值</p><p>B. 给 P 赋值为它的负数</p><p>C. P=0</p><p>D. P 等于它的负数</p></li></ol><ul><li>Python 中的 = 是赋值符号，== 是判断相等性的等于符号。</li></ul><ol start=7><li><p>哪个选项是用来判断当前 Python 语句在分支结构中？C</p><p>A. 冒号</p><p>B. 引号</p><p>C. 缩进</p><p>D. 大括号</p></li></ol><ul><li>缩进表达层次关系。</li></ul><ol start=8><li>哪个选项是下面代码的执行结果？D</li></ol><pre><code class=language-python>for s in &quot;PYTHON&quot; :
    if s == &quot;T&quot; :
        continue
    print(s,end=&quot;&quot;)
</code></pre><pre><code>A. TT

B. PYTHON

C. PY

D. PYHON
</code></pre><ul><li>continue 结束当次循环，但不跳出当前循环。</li></ul><ol start=9><li><p>哪个选项是 random 库中用于生成随机小数的函数？A</p><p>A. random()</p><p>B. randrange()</p><p>C. randint()</p><p>D. getrandbits()</p></li></ol><ul><li>randint()、getrandbits()、randrange() 都产生随机整数，random() 产生 0 到 1 之间的随机小数。</li></ul><ol start=10><li><p>关于 try-except，哪个选项的描述是错误的？B</p><p>A. 表达了一种分支结构的特点</p><p>B. 使用了异常处理，程序将不会再出错</p><p>C. NameError 是一种异常类型</p><p>D. 用于对程序的异常进行捕捉和处理</p></li></ol><ul><li>使用了异常处理，程序可能运行不会出错，但逻辑上可能出错。程序错误是一个大概念，不仅指代码运行错误，更代表功能逻辑错误。</li></ul></article><div class=my-4><a href=https://b.hui.ke/tags/%E5%88%86%E6%94%AF%E7%BB%93%E6%9E%84/ class="inline-block bg-tertiary-bg text-sm rounded px-3 py-1 my-1 me-2 hover:text-eureka">#分支结构</a>
<a href=https://b.hui.ke/tags/%E5%BE%AA%E7%8E%AF/ class="inline-block bg-tertiary-bg text-sm rounded px-3 py-1 my-1 me-2 hover:text-eureka">#循环</a>
<a href=https://b.hui.ke/tags/%E9%9A%8F%E6%9C%BA%E6%95%B0/ class="inline-block bg-tertiary-bg text-sm rounded px-3 py-1 my-1 me-2 hover:text-eureka">#随机数</a></div><div class=py-2><div class="my-8 flex flex-col items-center md:flex-row"><a href=https://b.hui.ke/authors/hui.ke/ class="md:me-4 text-primary-text h-24 w-24"><img src=https://b.hui.ke/bagua.webp class="bg-primary-bg w-full rounded-full" alt=Avatar></a><div class="mt-4 w-full md:mt-0 md:w-auto"><a href=https://b.hui.ke/authors/hui.ke/ class="mb-2 block border-b pb-1 text-lg font-bold"><h3>Hui.Ke</h3></a><span class="block pb-2">❤ Cyber Security | Safety is a priority.</span>
<a href=mailto:3199731997@qq.com class=me-2><i class="fas fa-envelope"></i></a>
<a href="https://wpa.qq.com/msgrd?v=3&uin=3199731997" class=me-2><i class="fab fa-qq"></i></a>
<a href=/images/aixinxianquan.webp class=me-2><i class="fab fa-weixin"></i></a></div></div></div><div class="-mx-2 mt-4 flex flex-col border-t px-2 pt-4 md:flex-row md:justify-between"><div><span class="text-primary-text block font-bold">Previous</span>
<a href=https://b.hui.ke/docs/python/14/ class=block>【第4周程序】程序的控制结构</a></div><div class="mt-4 md:mt-0 md:text-right"><span class="text-primary-text block font-bold">Next</span>
<a href=https://b.hui.ke/docs/python/13/ class=block>【第3周程序】基本数据类型</a></div></div><div id=valine-comments class=mt-4></div><script defer src=https://cdn.jsdelivr.net/npm/valine@1.4.16/dist/Valine.min.js integrity=sha384-e0+DNUCJo75aOAzHQbFWYBCM9/S4f0BhRJXvEgbE3mMS85RM20MSSGStHuNdY2QK crossorigin></script>
<script>document.addEventListener("DOMContentLoaded",function(){new Valine({el:"#valine-comments",appId:"BQnVqWIiq78AdqwyhvBVAa3y-MdYXbMMI",appKey:"RKg5By312YjM8rU6WkkfK9IN",recordIP:"true",serverURLs:"https://l.hui.ke",visitor:"true"})})</script></div><div class="hidden lg:block lg:w-1/4"><div class="bg-secondary-bg
prose sticky top-16 z-10 hidden px-6 py-4 lg:block"><h3>On This Page</h3></div><div class="sticky-toc
border-s
hidden px-6 pb-6 lg:block"><nav id=TableOfContents><ul><li><a href=#notes>Notes</a><ul><li><a href=#单分支结构>单分支结构</a></li><li><a href=#二分支结构>二分支结构</a></li><li><a href=#多分支结构>多分支结构</a></li><li><a href=#条件判断及组合>条件判断及组合</a></li><li><a href=#异常处理>异常处理</a></li><li><a href=#遍历循环>遍历循环</a></li><li><a href=#无限循环>无限循环</a></li><li><a href=#循环控制保留字>循环控制保留字</a></li><li><a href=#循环与-else>循环与 else</a></li><li><a href=#random-库基本介绍>random 库基本介绍</a></li><li><a href=#基本随机数函数>基本随机数函数</a></li><li><a href=#扩展随机数函数>扩展随机数函数</a></li></ul></li><li><a href=#测验-4>测验 4</a></li></ul></nav></div><script>window.addEventListener("DOMContentLoaded",()=>{enableStickyToc()})</script></div></div></div></div></div><script>document.addEventListener("DOMContentLoaded",()=>{hljs.highlightAll(),changeSidebarHeight(),switchDocToc()})</script></div></div></main><footer class=pl-scrollbar><div class="mx-auto w-full max-w-screen-xl"><div class="text-center p-6 pin-b"><script async src=/js/click.js></script><div id=poem_ip></div><script type=text/javascript>jinrishici.load(function(e){tags.innerHTML=e.data.matchTags})</script><div><span id=timeDate>载入年天数...</span><span id=times>载入时分秒...</span>
<script async src=/js/duration.js></script></div><a href=https://www.foreverblog.cn/go.html target=_blank><img src=https://img.foreverblog.cn/wormhole_4_tp.gif alt style=display:inline-block;width:auto;height:32px title=穿梭虫洞-随机访问十年之约友链博客></a><p class="text-sm text-tertiary-text"><script async src=//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js></script>本站总访问量 <span id=busuanzi_value_site_pv></span> 次
&#183; 您是本站的第 <span id=busuanzi_value_site_uv></span> 个小伙伴</p><script async src=/js/tab.js></script></div></div></footer></body></html>